package com.example.smart_video.ui.activity;

import static com.example.smart_video.adapter.HBomeListAdapter.SCENE_IMAGE_LIST;
import static com.example.smart_video.model.Constants.SHARE_PATH;
import static com.example.smart_video.model.Constants.TENCENT_BUCKET;
import static com.example.smart_video.model.Constants.TENCENT_BUCKET_OFFICE_URL;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.cleandemo3.R;
import com.example.cleandemo3.databinding.ActivityImageListBinding;
import com.example.smart_video.adapter.HBomeListAdapter;
import com.example.smart_video.model.Constants;
import com.example.smart_video.model.json.PictureData;
import com.example.smart_video.utils.AlbumNotifyHelper;
import com.example.smart_video.utils.HttpUtils;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.wink_172.library.activity.SmartActivity;
import com.wink_172.library.adapter.HomeListAdapter;
import com.wink_172.library.model.BaseDataItem;
import com.wink_172.library.utils.DateUtil;
import com.wink_172.library.utils.FileUtil;
import com.wink_172.library.utils.TencentCosUtils;
import com.wink_172.library.view.ActionBarView;

import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 *
 */
public class ImageListActivity extends SmartActivity {

    public ActivityImageListBinding binding;

    public static void startActivity(Activity context, Object... args) {
        Intent intent = new Intent(context, ImageListActivity.class);
        int mode = (Integer) args[0];


        intent.putExtra(com.wink_172.library.model.Constants.PARAM_DATA1, mode);

        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_image_list);

        initView();
        init();
    }

    void init() {
        setMode(getIntent().getIntExtra(com.wink_172.library.model.Constants.PARAM_DATA1, 0));
        getImageList();
    }

    public void initView() {
        binding.selectMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
                homeListAdapter.setListSelect(true);
                homeListAdapter.notifyDataSetChanged();
            }
        });

        binding.unselectMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
                homeListAdapter.setListSelect(false);
                homeListAdapter.notifyDataSetChanged();
            }
        });

        binding.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
                List<Object> list = homeListAdapter.getDataList();
//              BaseDataItem baseDataItem = (BaseDataItem) list.get(position);
                Log.e(TAG, "onClick: ====>>删除按钮" );
                List<String>  image_urls=new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    BaseDataItem baseDataItem = (BaseDataItem) list.get(i);
                    if(baseDataItem.getSelect()){
                        PictureData videoClassData = (PictureData) baseDataItem.getData();

                        String temp="/image-all/"+FileUtil.Companion.getFileNameWithSuffix(videoClassData.image_url);
                        image_urls.add(temp);
                        Log.e(TAG, "image_url2: ====>>"+temp );
//                      videoClassData.image_url
                    }
                }

                //删除操作
                TencentCosUtils.deleteBucketFile(image_urls, TENCENT_BUCKET,
                        new com.wink_172.library.callback.ICallback() {
                            @Override
                            public void onSendEvent(int event, @NonNull Object... objects) {

                                Log.e(TAG, "onSendEvent: ====>>"+event );
                                getImageList();
                            }
                        });


            }
        });

        binding.down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClick: ====>>下载按钮" );
                HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
                List<Object> list = homeListAdapter.getDataList();
//              BaseDataItem baseDataItem = (BaseDataItem) list.get(position);
                for (int i = 0; i < list.size(); i++) {
                    BaseDataItem baseDataItem = (BaseDataItem) list.get(i);
                    if(baseDataItem.getSelect()){
                        PictureData videoClassData = (PictureData) baseDataItem.getData();
                        //已经下载好到私有目录的，拷贝到sd卡即可
                        String sd_file_path= Environment.getExternalStorageDirectory().getAbsolutePath() +
                                "/Download/"+FileUtil.Companion.getFileNameWithSuffix(videoClassData.image_url);
//                        Log.e(TAG, "onClick: ====>>下载按钮" +videoClassData.image_url+"   "+videoClassData.local_url);
                       Boolean result= FileUtil.Companion.copyFile(videoClassData.local_url,sd_file_path);
                       if(result){
                           AlbumNotifyHelper.insertImageToMediaStore(x.app(), sd_file_path,System.currentTimeMillis());
                       }
                    }
                }
            }
        });
        ((ActionBarView) binding.actionBar).content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getImageList();
            }
        });

        ((ActionBarView) binding.actionBar).updateAllContent(R.mipmap.icon_nav_arrow, "", "上传");
        ((ActionBarView) binding.actionBar).setCallback(new ActionBarView.ICallback() {
            @Override
            public void onSendEvent(int event, String content) {
                if (event == ActionBarView.LEFT_BTN) {
                    finish();

                } else if (event == ActionBarView.RIGHT_BTN) {
                    //上传
                    selImages();

                }
            }
        });


        List<Object> list = new ArrayList();
        HBomeListAdapter homeListAdapter = new HBomeListAdapter(this, list, binding.listView);
        binding.listView.init(homeListAdapter, false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 6, GridLayoutManager.VERTICAL, false);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
//                if (position < 7 || position > 14) {
//                    return 3;
//                }
                return 2;
            }
        });
        binding.listView.setLayoutManager(gridLayoutManager);
    }

    public void selImages() {
        PictureSelector.create(getActivity())
                .openSystemGallery(SelectMimeType.ofImage())
                .forSystemResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {

                        for (int i = 0; i < result.size(); i++) {
                            LocalMedia single = result.get(i);

                            String local_path = single.getRealPath();
                            Log.e(TAG, "single: ====>>" + local_path);

                            uploadFile(local_path);
                        }

                        x.task().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getImageList();
                            }
                        },2000);
                        x.task().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getImageList();
                            }
                        },4000);
                        x.task().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getImageList();
                            }
                        },6000);
                        x.task().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getImageList();
                            }
                        },8000);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    /**
     * UUID  文件名
     * type       1视频  2视频略缩图
     * filePath 本地文件的绝对路径
     * <p>
     * 请注意任何上传文件均不能带有中文名称，否则删除腾讯云会失败（虽然提示成功但实际上未成功）    a5d85b7QQ空间视频_20210514183635.mp4
     */
    private void uploadFile(String filePath) {
        Log.e(TAG, "uploadFile: ====>>" + filePath);
        String name = UUID.randomUUID().toString();//确保视频和图片名称一致
        String childFolder = DateUtil.longToString(System.currentTimeMillis(),
                DateUtil.FORMAT_DATE) + "/";


        String cosPath = "image-all/" + name + "." +
                FileUtil.Companion.getExtensionName(filePath);
        ; //对象在存储桶中的位置标识符，即称对象键

        TencentCosUtils.uploadTectentFile(cosPath, filePath, TENCENT_BUCKET,

                new com.wink_172.library.callback.ICallback() {
                    @Override
                    public void onSendEvent(int event, @NonNull Object... objects) {
                        if (event == com.wink_172.library.model.Constants.EventEnum.上传成功.ordinal()) {
//                            FileUtil.Companion.delete(filePath);//用完就删
                            hideProgressDialog();

                        } else if (event == com.wink_172.library.model.Constants.EventEnum.上传失败.ordinal()) {
                            hideProgressDialog();
                        }

                    }
                }
        );


    }

    private static final String TAG = "ImageListActivity";

    /**
     * 获取图库列表
     */
    private void getImageList() {

        HttpUtils.INSTANCE.get_test_imge_list(new com.wink_172.library.callback.ICallback() {
            @Override
            public void onSendEvent(int event, @NonNull Object... objects) {
                if (event == Constants.EventEnum.网络请求成功.ordinal()) {

                    List videoDataList = (List) objects[0];
                    Log.e(TAG, "onSendEvent: ====>>size:" + videoDataList.size());
                    initImageList(videoDataList);
                }
            }
        });

    }

    int count = 0;

    public void initImageList(List<PictureData> classList) {
        List<Object> list = new ArrayList<Object>();
        count = 0;
        ((ActionBarView) binding.actionBar).content.setText("图库(" + classList.size() + ")");

        for (int i = 0; i < classList.size(); i++) {
            PictureData videoClassData = classList.get(i);
            BaseDataItem baseDataItem = new BaseDataItem(i, SCENE_IMAGE_LIST);

            HBomeListAdapter homeListAdapter = (HBomeListAdapter) binding.listView.getAdapter();
            homeListAdapter.setMOnItemClickListener(new HomeListAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(@Nullable View view, int pos) {

                    if (homeListAdapter.isListSelect()) {
                        BaseDataItem baseDataItem = (BaseDataItem) homeListAdapter.getDataList().get(pos);

                        baseDataItem.setSelect(baseDataItem.getSelect()==false);//反选
                        homeListAdapter.notifyItemChanged(pos);

                    } else {
                        BaseDataItem baseDataItem = (BaseDataItem) homeListAdapter.getDataList().get(pos);
                        PictureData videoClassData = (PictureData) baseDataItem.getData();
                        PlayImageActivity.startActivity(getActivity(), videoClassData.local_url);
                    }
                }
            });


            String image = TENCENT_BUCKET_OFFICE_URL + videoClassData.image_url.replace("/down/" + SHARE_PATH + "?fname=/", "image-all/");
            String loacl_path = x.app().getCacheDir().getPath() + FileUtil.Companion.getFileNameWithSuffix(image);
//            videoClassData.image_url2=""+videoClassData.image_url;//原图地址

            File file = new File(loacl_path);
            if (file.exists()) {
                count += 1;
                videoClassData.local_url = loacl_path;
                baseDataItem.setObjectData(videoClassData);

                list.add(0, baseDataItem);

                if (count == list.size()) {

                    homeListAdapter.swapContent(list);
                    homeListAdapter.notifyDataSetChanged();
                }
            } else {
                HttpUtils.INSTANCE.downLoadFile(image, loacl_path,
                        new com.wink_172.library.callback.ICallback() {
                            @Override
                            public void onSendEvent(int event, @NonNull Object... objects) {
                                if (event == Constants.EventEnum.网络请求成功.ordinal()) {
                                    videoClassData.local_url = loacl_path;
                                    baseDataItem.setObjectData(videoClassData);

                                    list.add(0, baseDataItem);
                                }
                                if (event == Constants.EventEnum.网络请求完成.ordinal()) {
                                    count += 1;
                                    if (count == list.size()) {

                                        homeListAdapter.swapContent(list);
                                        homeListAdapter.notifyDataSetChanged();
                                    }
                                }
                            }
                        }
                );
            }


        }


    }

}